package com.api.shopapi.controller;

import com.alibaba.fastjson.JSONObject;
import com.api.shopapi.entity.*;
import com.api.shopapi.entity.dto.BerthDTO;
import com.api.shopapi.entity.dto.BuildingDTO;
import com.api.shopapi.entity.dto.RoomDTO;
import com.api.shopapi.service.*;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @author maochuan
 * 床位
 */
@RestController
@RequestMapping("Berth")
public class BerthController extends BaseController {

    @Autowired
    @Qualifier("BerthServiceImplOne")
    private BerthService berthService;

    @Autowired
    @Qualifier("StaffServiceImplOne")
    private StaffService staffService;

    @Autowired
    @Qualifier("RoomServiceImplOne")
    private RoomService roomService;

    @Autowired
    @Qualifier("RoomTypeServiceImplOne")
    private RoomTypeService roomTypeService;

    @Autowired
    @Qualifier("BuildingServiceImplOne")
    private BuildingService buildingService;

    @Autowired
    @Qualifier("InstitutionStaffRelServiceImplOne")
    private InstitutionStaffRelService institutionStaffRelService;


    @Autowired
    @Qualifier("CheckinSetmealServiceImplOne")
    private CheckinSetmealService checkinSetmealService;


    @RequestMapping(value = "Pannel", method = RequestMethod.POST)
    public MyResult Pannel(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");


            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Berth/Pannel");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            InstitutionStaffRel institutionStaffRel = institutionStaffRelService.getByStaffCode(staffCode);
            String institutionCode = institutionStaffRel.getInstitutionCode();

            List<Berth> listBerth = berthService.ListByInstitutionCode(institutionCode);

            List<Berth> listBerthCheckin = berthService.ListCheckinByInstitutionCode(institutionCode);

            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("berthCount",listBerth.size());
            jsonObject1.put("berthCountCheckin",listBerthCheckin.size());
            return success(jsonObject1);
        } catch (Exception e) {
            insertError("/Berth/Pannel", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }

    }




    @RequestMapping(value = "Add", method = RequestMethod.POST)
    public MyResult Insert(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            String roomCode = jsonObject.getString("roomCode");
            String number = jsonObject.getString("number");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Berth/Add");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }


            InstitutionStaffRel institutionStaffRel = institutionStaffRelService.getByStaffCode(staffCode);
            String institutionCode = institutionStaffRel.getInstitutionCode();


            Room room = roomService.getByRoomCode(roomCode);
            if (room == null) {
                return failed("房间不存在");
            }
            RoomType roomType = roomTypeService.getByRoomTypeCode(room.getRoomTypeCode());
            int num = roomType.getNum();
            List<Berth> berthList = berthService.getListByRoomCode(roomCode);
            if(berthList.size()>=num){
                return failed("该房间床位数量已满");
            }
            String roomNumber = room.getNumber();
            Berth berth = berthService.getByNumber(number, roomCode, institutionCode);
            if (berth != null) {
                return failed("床位已存在");
            }

            berth = new Berth();
            berth.setStaffCode(staffCode);
            berth.setBerthCode(UUID.randomUUID().toString());
            berth.setRoomCode(roomCode);
            berth.setRoomNumber(roomNumber);
            berth.setRoomFloor(room.getFloor());
            berth.setNumber(number);
            berth.setStatus(0);
            berth.setInstitutionCode(institutionCode);
            berthService.insert(berth);
            Object data = new Object[]{};
            return success(data);

        } catch (Exception e) {
            insertError("/Berth/Add", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }

    }

    @RequestMapping(value = "Edit", method = RequestMethod.POST)
    public MyResult UpdateByberthCode(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");
            String roomCode = jsonObject.getString("roomCode");
            String number = jsonObject.getString("number");
            int status = jsonObject.getInteger("status");
            String berthCode = jsonObject.getString("berthCode");
            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Berth/Edit");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            InstitutionStaffRel institutionStaffRel = institutionStaffRelService.getByStaffCode(staffCode);
            String institutionCode = institutionStaffRel.getInstitutionCode();

            Room room = roomService.getByRoomCode(roomCode);
            if (room == null) {
                return failed("房间不存在");
            }

            String roomNumber = room.getNumber();
            Berth berth = berthService.getByBerthCode(berthCode);
            if (berth == null) {
                return failed("床号不存在");
            } else {
                if(!berth.getRoomCode().equals(roomCode)){
                    RoomType roomType = roomTypeService.getByRoomTypeCode(room.getRoomTypeCode());
                    int num = roomType.getNum();
                    List<Berth> berthList = berthService.getListByRoomCode(roomCode);
                    if(berthList.size()>=num){
                        return failed("该房间床位数量已满");
                    }
                }
                if(status==11){
                    if(berth.getStatus()==2){
                        return failed("已入住状态下不允许禁用");
                    }
                }
                Berth berth1 = berthService.getByNumber(number, roomCode, institutionCode);
                if(berth1!=null){
                    if (!berth.getBerthCode().equals(berth1.getBerthCode())) {
                        return failed("床位已存在");
                    }
                }
                berth.setRoomCode(roomCode);
                berth.setRoomNumber(roomNumber);
                berth.setRoomFloor(room.getFloor());
                berth.setNumber(number);
                berth.setStatus(status);
                berth.setInstitutionCode(institutionCode);
                berthService.updateByBerthCode(berth);
            }
            Object data = new Object[]{};
            return success(data);
        } catch (Exception e) {
            insertError("/Berth/Edit", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }

    }

    @RequestMapping(value = "Page", method = RequestMethod.POST)
    public MyResult GetListByInstitutionCode(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            String roomCode = jsonObject.getString("roomCode");
            int number = jsonObject.getInteger("number");
            int status = jsonObject.getInteger("status");
            int pageIndex = jsonObject.getInteger("pageIndex");
            int pageSize = jsonObject.getInteger("pageSize");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Berth/Page");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }


            InstitutionStaffRel institutionStaffRel = institutionStaffRelService.getByStaffCode(staffCode);
            String institutionCode = institutionStaffRel.getInstitutionCode();

            //床位列表
            PageInfo<Berth> pageInfoBerth = berthService.getPageList(pageIndex, pageSize, institutionCode,number,roomCode,status);

            //房间扩展列表
            List<BerthDTO> listBerthDTO = new ArrayList<>();
            for (Berth berth:pageInfoBerth.getList()){
                BerthDTO berthDTO = mapper.map(berth, BerthDTO.class);
                listBerthDTO.add(berthDTO);
            }
            for (BerthDTO berthDTO:listBerthDTO){
                Room room = roomService.getByRoomCode(berthDTO.getRoomCode());
                Building building = buildingService.getByBuildingCode(room.getBuildingCode());
                berthDTO.setBuilding(building);
            }
            pageInfoBerth.setList(Collections.unmodifiableList(listBerthDTO));
            return success(pageInfoBerth);
        } catch (Exception e) {
            insertError("/Berth/Page", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }

    }

    @RequestMapping(value = "GovPage", method = RequestMethod.POST)
    public MyResult GovPage(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            String roomCode = jsonObject.getString("roomCode");
            int number = jsonObject.getInteger("number");
            int status = jsonObject.getInteger("status");
            int pageIndex = jsonObject.getInteger("pageIndex");
            int pageSize = jsonObject.getInteger("pageSize");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Berth/Page");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }


            Staff staff = staffService.getByStaffCode(staffCode);

            //床位列表
            PageInfo<Berth> pageInfoBerth = berthService.pageByGovCode(pageIndex, pageSize, staff.getGovernmentCode());

            //房间扩展列表
            List<BerthDTO> listBerthDTO = new ArrayList<>();
            for (Berth berth:pageInfoBerth.getList()){
                BerthDTO berthDTO = mapper.map(berth, BerthDTO.class);
                listBerthDTO.add(berthDTO);
            }
            for (BerthDTO berthDTO:listBerthDTO){
                Room room = roomService.getByRoomCode(berthDTO.getRoomCode());
                Building building = buildingService.getByBuildingCode(room.getBuildingCode());
                berthDTO.setBuilding(building);
            }
            pageInfoBerth.setList(Collections.unmodifiableList(listBerthDTO));

            return success(pageInfoBerth);
        } catch (Exception e) {
            insertError("/Berth/Page", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }

    }





    //查询可入住的全部 楼宇、房间、床位(3级一起查)
    @RequestMapping(value = "ListAll", method = RequestMethod.POST)
    public MyResult ListAll(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");
            String berthCode = jsonObject.getString("berthCode");
            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Berth/ListAll");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }


            InstitutionStaffRel institutionStaffRel = institutionStaffRelService.getByStaffCode(staffCode);
            String institutionCode = institutionStaffRel.getInstitutionCode();



            String roomCode1 = "";
            Berth berth = null;
            if(!berthCode.equals("")&&!berthCode.equals("00000000-0000-0000-0000-000000000000")){
                berth = berthService.getByBerthCode(berthCode);
                if(berth.getStatus()!=11){
                    Room room = roomService.getByRoomCode(berth.getRoomCode());
                    roomCode1 = room.getRoomCode();
                }

            }

            //楼宇列表
            List<Building> listBuilding = buildingService.getListAllByInstitutionCode(institutionCode);
            //楼宇扩展列表
            List<BuildingDTO> listBuildingDTO = new ArrayList<>();

            for (Building building : listBuilding) {
                BuildingDTO buildingDTO = mapper.map(building, BuildingDTO.class);
                listBuildingDTO.add(buildingDTO);
            }


            for (BuildingDTO buildingDTO : listBuildingDTO) {
                //房间列表
                List<Room> listRoom = roomService.getListByBuildingCodeAndStatusNot1(buildingDTO.getBuildingCode());

                //房间扩展列表
                List<RoomDTO> listRoomDTO = new ArrayList<>();

                for (Room room : listRoom) {
                    RoomDTO roomDTO = mapper.map(room, RoomDTO.class);
                    listRoomDTO.add(roomDTO);
                }

                for (RoomDTO roomDTO : listRoomDTO) {
                    //床位列表
                    List<Berth> listBerth = berthService.getListByRoomCodeAndStatus0(roomDTO.getRoomCode());
                    if(roomCode1!=""){
                        if(roomDTO.getRoomCode().equals(roomCode1)){
                            listBerth.add(berth);
                        }
                    }
                    roomDTO.setListBerth(listBerth);

                }
                buildingDTO.setListRoomDTO(listRoomDTO);

            }


            return success(listBuildingDTO);
        }catch (Exception e){
            insertError("/Berth/ListAll", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }


    //根据房间类型查询可入住的全部 楼宇、房间、床位(3级一起查)
    @RequestMapping(value = "ListBerth", method = RequestMethod.POST)
    public MyResult ListBerth(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            String berthCode = jsonObject.getString("berthCode");
            String checkinSetmealCode = jsonObject.getString("checkinSetmealCode");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Berth/ListBerth");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }


            InstitutionStaffRel institutionStaffRel = institutionStaffRelService.getByStaffCode(staffCode);
            String institutionCode = institutionStaffRel.getInstitutionCode();



            CheckinSetmeal checkinSetmeal = checkinSetmealService.getByCheckinSetmealCode(checkinSetmealCode);

            RoomType roomType = roomTypeService.getByRoomTypeCode(checkinSetmeal.getRoomTypeCode());
            int num = roomType.getNum();

            String roomCode1 = "";
            Berth berth = null;
            if(!berthCode.equals("")&&!berthCode.equals("00000000-0000-0000-0000-000000000000")){
                berth = berthService.getByBerthCode(berthCode);
                if(berth.getStatus()!=11){
                    Room room = roomService.getByRoomCode(berth.getRoomCode());
                    roomCode1 = room.getRoomCode();
                }

            }

            //楼宇列表
            List<Building> listBuilding = buildingService.getListAllByInstitutionCode(institutionCode);
            //楼宇扩展列表
            List<BuildingDTO> listBuildingDTO = new ArrayList<>();

            for (Building building : listBuilding) {
                BuildingDTO buildingDTO = mapper.map(building, BuildingDTO.class);
                listBuildingDTO.add(buildingDTO);
            }

            for (BuildingDTO buildingDTO : listBuildingDTO) {
                //房间列表
                List<Room> listRoom = roomService.getListByBuildingCodeAndNumAndStatusNot1(buildingDTO.getBuildingCode(),num);

                //房间扩展列表
                List<RoomDTO> listRoomDTO = new ArrayList<>();

                for (Room room : listRoom) {
                    RoomDTO roomDTO = mapper.map(room, RoomDTO.class);
                    listRoomDTO.add(roomDTO);
                }

                for (RoomDTO roomDTO : listRoomDTO) {
                    //床位列表
                    List<Berth> listBerth = berthService.getListByRoomCodeAndStatus0(roomDTO.getRoomCode());
                    if(roomCode1!=""){
                        if(roomDTO.getRoomCode().equals(roomCode1)){
                            listBerth.add(berth);
                        }
                    }
                    roomDTO.setListBerth(listBerth);

                }
                buildingDTO.setListRoomDTO(listRoomDTO);

            }


            return success(listBuildingDTO);
        }catch (Exception e){
            insertError("/Berth/ListBerth", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }



    /**
     * 查询所有楼宇，房间，床位（房态图用）
     * @param jsonObject
     * @return
     */
    @RequestMapping(value = "roomStateDiagram", method = RequestMethod.POST)
    public MyResult roomStateDiagram(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");
            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Berth/roomStateDiagram");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            InstitutionStaffRel institutionStaffRel = institutionStaffRelService.getByStaffCode(staffCode);
            String institutionCode = institutionStaffRel.getInstitutionCode();

            List<Building> buildingList = buildingService.getListAllByInstitutionCode(institutionCode);
            List<BuildingDTO> buildingDTOList = new ArrayList<>();
            for(Building building:buildingList){
                BuildingDTO buildingDTO = mapper.map(building,BuildingDTO.class);

                buildingDTOList.add(buildingDTO);
            }

            for(BuildingDTO buildingDTO:buildingDTOList){
                List<Room> roomList = roomService.getListByBuildingCode(buildingDTO.getBuildingCode());
                List<RoomDTO> roomDTOList = new ArrayList<>();
                for(Room room:roomList){
                    RoomDTO roomDTO = mapper.map(room,RoomDTO.class);
                    roomDTOList.add(roomDTO);
                }
                for(RoomDTO roomDTO:roomDTOList){
                    List<Berth> berthList = berthService.getListByRoomCode(roomDTO.getRoomCode());
                    List<BerthDTO> berthDTOList = new ArrayList<>();
                    for(Berth berth:berthList){
                        BerthDTO berthDTO = mapper.map(berth,BerthDTO.class);
                        berthDTOList.add(berthDTO);

                    }
//                    for(BerthDTO berthDTO:berthDTOList){
//                        if(berthDTO.getStatus()==1){
//                            CheckinDTO2 checkinDTO2 = checkinService.getByBerth(berthDTO.getBerthCode(),0);
//                            if(checkinDTO2!=null){
//                                Map<String, Object> carInfo = CardUtil.getCarInfo(checkinDTO2.getIdCard());
//                                checkinDTO2.setAge((Integer) carInfo.get("age"));
//                            }
//                            berthDTO.setCheckin(checkinDTO2);
//                        }
//                        if(berthDTO.getStatus()==2){
//                            CheckinDTO2 checkinDTO2 = checkinService.getByBerth(berthDTO.getBerthCode(),1);
//                            if(checkinDTO2!=null){
//                                Map<String, Object> carInfo = CardUtil.getCarInfo(checkinDTO2.getIdCard());
//                                checkinDTO2.setAge((Integer) carInfo.get("age"));
//                            }
//                            berthDTO.setCheckin(checkinDTO2);
//                        }
//                    }
                    roomDTO.setListBerthDTO(berthDTOList);
                }
                buildingDTO.setListRoomDTO(roomDTOList);
            }
            return success(buildingDTOList);
        }catch (Exception e){
            insertError("/Berth/roomStateDiagram", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }



}
